import { config, loadRemote, loadCssRemote } from '@vimi/utils-tool'

let instance

const createViewer = async () => {
  if (instance) return
  const viewPath = config.baseUrl + '/libs/viewer/1.7.1/'
  await Promise.all([
    loadRemote(viewPath + 'viewer.min.js'),
    loadCssRemote(viewPath + 'viewer.min.css'),
  ])
  const container = document.createElement('div')
  container.classList.add('img-viewer-container')
  document.body.appendChild(container)
  instance = new window.Viewer(container, {
    zIndex: 5000,
  })
}

const viewer = async ({ images = [], visible = true, index = 0 } = {}) => {
  await createViewer()

  if (typeof images === 'string') {
    images = [images]
  }

  if (index < 0) {
    index = 0
  } else if (index > images.length - 1) {
    index = images.length - 1
  }

  const imgEls = images.map(it => {
    if (typeof it === 'string') {
      it = { url: it, title: '' }
    }
    return `
    <div class="img-viewer-item">
      <img src="${it.url || it.src}" alt="${it.title || it.name || ''}">
    </div>`
  })
  instance.element.innerHTML = `<div class="img-viewer-wrapper">${imgEls}</div>`

  if (visible) {
    instance.update()
    instance.view(index)
  }

  return instance
}

export default viewer
